package com.browsesoft.arrange;

import java.util.LinkedList;

import com.browsesoft.SequenceFind;

public class Arrange {
	private static LinkedList arranges = new LinkedList();

	// 唯一id
	private String ID = "";

	// 他的子
	LinkedList children = new LinkedList();

	// 它的父

	private Arrange parent = null;

	// 名字，比如“任务状态”，它对应的数据库字段名为“select1”
	private String name = "";

	// 数据库对应的字段名
	private String fieldName = "";

	// 是否是一个根，比如说“任务状态”就是一个根，
	private boolean isRoot = false;

	public Arrange(String n, String field) throws Exception {
		name = n;
		this.fieldName = field;
		// 设置ID
		ID = Integer.toString(SequenceFind.getID());
		arranges.add(this);
	}

	public String getID() {
		return ID;
	}

	public void add(Arrange child) {
		// 设置父
		child.setParent(this);
		children.add(child);
	}

	public LinkedList getChildren() {
		return this.children;
	}

	public String getName() {
		return this.name;
	}

	public String getFieldName() {
		return this.fieldName;
	}

	public void setParent(Arrange p) {
		this.parent = p;
	}

	public Arrange getParent() {
		return this.parent;
	}

	public Arrange getGranddad() {
		if (this.getParent() == null) {
			return null;
		} else {
			return this.getParent().getParent();
		}
	}

	public static Arrange getArrange(String id) {
		System.out.println("size:" + arranges.size());
		for (int i = 0; i < arranges.size(); i++) {
			Arrange a = (Arrange) arranges.get(i);
			if (a.getID().equals(id)) {
				return a;
			}
		}
		return null;
	}

	public void setRoot(boolean b) {
		this.isRoot = b;
	}

	public boolean isRoot() {
		return this.isRoot;
	}

	public LinkedList getGardensons(int index) {
		LinkedList v = new LinkedList();
		if (index == 0) {
			v.add(this);
			return v;
		} else {
			return this.getGardensons(this, index);
		}
	}

	public LinkedList getGardensons(Arrange arrange, int level) {
		if (level == 1) {
			return arrange.getGardensons();
		} else {
			LinkedList v = new LinkedList();
			for (int i = 0; i < arrange.getGardensons().size(); i++) {
				v.addAll(getGardensons(
						(Arrange) arrange.getGardensons().get(i), level - 1));
			}
			return v;
		}
	}

	public LinkedList getGardensons() {
		LinkedList v = new LinkedList();
		LinkedList children = this.getChildren();
		for (int i = 0; i < children.size(); i++) {
			Arrange child = (Arrange) children.get(i);
			v.addAll(child.getChildren());
		}
		return v;
	}
}
